#include "include/majorsystemui.h"
#include "ui_majorsystemui.h"

#include <QString>
#include <QDebug>
#include <QFile>
#include <QPair>

#include <algorithm>

MajorSystemUI::MajorSystemUI(QWidget *parent) :
	QWidget(parent),
	ui(new Ui::MajorSystemUI)
{
	ui->setupUi(this);

	QRegExpValidator* v = new QRegExpValidator(QRegExp("[0-9]\\d{0,100}"), 0);
	ui->w_number->setValidator(v);

	connect(ui->w_number, SIGNAL(textChanged(const QString&)), this, SLOT(update(const QString&)));
	connect(ui->w_numMajorSounds, SIGNAL(valueChanged(const QString&)), this, SLOT(update(const QString&)));
}

MajorSystemUI::~MajorSystemUI()
{
	delete ui;
}

void MajorSystemUI::update(const QString&)
{
	static bool dictionaryInitialised = false;

	if (!dictionaryInitialised)
	{
		QFile file(":/resources/dictionary.txt");
		if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
			return;

		QTextStream in(&file);
		while (!in.atEnd())
		{
			QString line = in.readLine();
			MajorSystemWord word(line);
			m_words.insert(word.getNum(), word);
		}
		dictionaryInitialised = true;
	}

	//int numSounds = ui->w_numMajorSounds->value();
	QString trimmedStr = ui->w_number->text().left(ui->w_numMajorSounds->value());
	ui->w_comboBox->clear();
	QList<MajorSystemWord> values = m_words.values(trimmedStr);
	qSort(values);
	for (int i = 0; i < values.size(); ++i)
		ui->w_comboBox->addItem(values[i].getWord());
}

void MajorSystemUI::on_useButton_clicked()
{
	QString word = ui->w_comboBox->currentText();
	QString text = ui->w_number->text();
	unsigned int numNumbers = ui->w_numMajorSounds->value();
	QString toTake = ui->w_number->text().left(numNumbers);
	QString toLeave = ui->w_number->text().right(text.size() - toTake.size());
	ui->w_number->clear();
	ui->w_number->insert(toLeave);
	ui->w_number_done->insert(toTake);
	ui->w_results->insertPlainText(word+" ");
}

void MajorSystemUI::on_pushButton_clicked()
{
	QString resultSoFar = ui->w_number_done->text();
	QString text = ui->w_number->text();
	ui->w_number->clear();
	ui->w_number_done->clear();
	ui->w_results->clear();
	ui->w_number->insert(resultSoFar + text);
}
